package com.rainbow.security;

import cn.hutool.core.lang.Console;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rainbow.common.UserUtils;
import com.rainbow.config.AuthenticationAccessDeniedHandler;
import com.rainbow.config.CustomMetadataSource;
import com.rainbow.config.UrlAccessDecisionManager;
import com.rainbow.expetion.MyException;
import com.rainbow.jwt.SuccessHandler;
import com.rainbow.jwt.TokenAuthorizationFilter;
import com.rainbow.service.UserService;
import com.rainbow.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;

/**
 * @Author rainbow
 **/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    CustomMetadataSource metadataSource;
    @Autowired
    UrlAccessDecisionManager urlAccessDecisionManager;
    @Autowired
    AuthenticationAccessDeniedHandler deniedHandler;

    @Autowired
    private TokenAuthorizationFilter tokenAuthorizationFilter;

    @Autowired
    private SuccessHandler successHandler;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/index.html", "/static/**", "/login_p", "/druid/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(metadataSource);
                        o.setAccessDecisionManager(urlAccessDecisionManager);
                        return o;
                    }
                })
                .and()
                .addFilterBefore(tokenAuthorizationFilter, UsernamePasswordAuthenticationFilter.class)
                //.sessionManagement().sessionCreationPolicy(STATELESS)
                .formLogin().loginPage("/login").loginProcessingUrl("/login")
                .usernameParameter("username").passwordParameter("password")
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req,
                                                        HttpServletResponse resp,
                                                        AuthenticationException e) throws IOException {
                        resp.setContentType("application/json;charset=utf-8");
                        if (e instanceof BadCredentialsException ||
                                e instanceof UsernameNotFoundException) {
                            throw new MyException("账户名或者密码输入错误!");
                        } else if (e instanceof LockedException) {
                            throw new MyException("账户被锁定，请联系管理员!");
                        } else if (e instanceof CredentialsExpiredException) {
                            throw new MyException("密码过期，请联系管理员!");
                        } else if (e instanceof AccountExpiredException) {
                            throw new MyException("账户过期，请联系管理员!");
                        } else if (e instanceof DisabledException) {
                            throw new MyException("账户被禁用，请联系管理员!");
                        } else {
                            throw new MyException("登录失败!");
                        }
                    }
                })
                //.successHandler((AuthenticationSuccessHandler) (req, resp, auth) -> Console.log("登录成功:" + UserUtils.getCurrentHr()))
                .successHandler(successHandler)
                .permitAll()
                .and()
                .logout().permitAll()
                .and().csrf().disable()
                .exceptionHandling().accessDeniedHandler(deniedHandler);
    }
}
